import { trim, isEmpty } from 'lodash';
import { Op } from 'sequelize';
import BaseController from './base';
import SmsSignModel from '../models/sms-sign';
import Client from '../utils/sms';
import dayjs from 'dayjs';

// order docs https://sequelize.org/docs/v6/core-concepts/model-querying-basics/
class SmsSignController extends BaseController {
  getModel() {
    return SmsSignModel;
  }

  /**
   * 解析查询条件
   * @returns {Object}
   */
  getFindWhere(req) {
    const {
      nickname, openid,
    } = req.query;
    const { hotel_id } = req.user;

    const where = { hotel_id };
    if (openid) {
      where.openid = openid;
    }

    if (trim(nickname)) {
      where.nickname = trim(nickname);
    }

    return { where };
  }

  async create(req, res, next) {
    try {
      const { signName, remark, signType, moreData, qualificationId, applySceneContent, signSource, thirdParty } = req.body;

      const client = Client.createDysmsapiClient();
      const response = await Client.createSmsSign(client, signName, remark, signType, moreData, qualificationId, applySceneContent, signSource, thirdParty);
      if (response) {
        if (response.statusCode === 200) {
          if (response.body.code === 'OK') {
            req.body.orderId = response.body.orderId;
            req.body.requestId = response.body.requestId;
            req.body.signName = response.body.signName;
            req.body.createDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
          } else {
            throw new Error('申请短信签名失败: ' + response.body.message);
          }
        } else {
          throw new Error('请求短信平台失败, statusCode: ' + response.statusCode);
        }
      } else {
        throw new Error('请求短信平台失败: 未知错误');
      }
      const model = this.getModel();

      const transaction = await getSequelize().transaction();
      req.transaction = transaction;
      const data = await model.create(req.body, { req, transaction });
      await transaction.commit();
      res.sendOk(data);
    }
    catch (e) {
      next(e);
    }
  }
}

export default new SmsSignController();
